import os
import tkinter as tk
import sys
from pathlib import Path
from openpyxl import Workbook
from datetime import datetime
from tkinter import ttk, filedialog, messagebox


class DocCheckApp:
    def __init__(self, root):
        self.root = root
        self.root.title("文档检查工具合集")
        self.excel_path = tk.StringVar()
        self.docs_path = tk.StringVar()

        # 获取当前文档责任田
        ttk.Label(root, text="排查当前文档中的编码格式错误问题").grid(row=4, column=1, padx=5, pady=5)
        ttk.Label(root, text="会生成Excel在工具所在路径下").grid(row=5, column=1, padx=5, pady=5)
        ttk.Label(root, text="文档仓路径:").grid(row=6, column=0, padx=5, pady=5)
        ttk.Entry(root, textvariable=self.docs_path, width=50).grid(row=6, column=1, padx=5, pady=5)
        ttk.Button(root, text="浏览", command=self.select_directory).grid(row=6, column=2, padx=5, pady=5)

        ttk.Button(root, text="获取文档责任田", command=self.run_get_owner).grid(row=7, column=1, pady=10, padx=5)

    def select_directory(self):
        path = filedialog.askdirectory()
        if path:
            self.docs_path.set(path)

    def run_get_owner(self):
        """执行未标签内容检查"""
        if not self.validate_docs_path():
            return
        try:
            get_owner(self.docs_path.get())  # 假设tool.py的main函数已适配
            self.show_success("责任田表格生成", self.docs_path.get())
        except Exception as e:
            messagebox.showerror("错误", str(e))

    def validate_docs_path(self):
        """验证路径有效性"""
        if not self.docs_path.get():
            messagebox.showwarning("警告", "请先docs仓路径")
            return False
        return True

    def validate_excel_path(self):
        """验证路径有效性"""
        if not self.excel_path.get():
            messagebox.showwarning("警告", "请先选择excel路径")
            return False
        return True

    def show_success(self, check_type, path):
        """显示成功提示"""
        messagebox.showinfo("完成",
                            f"{check_type}检查完成！\n结果文件路径:\n{path}")


def get_owner(git_path):
    print("main")
    if not os.path.exists(git_path):
        raise FileNotFoundError(f"文档仓路径不存在：{git_path}")

    now = datetime.now()
    # 获取 exe 所在目录（兼容打包前后两种环境）
    if getattr(sys, 'frozen', False):
        current_dir = os.path.dirname(sys.executable)  # 打包后 exe 路径
    else:
        current_dir = os.path.dirname(os.path.abspath(__file__))  # 开发环境路径

    # 拼接 Excel 文件路径，得到输出信息位置
    excel_path = os.path.join(current_dir, 'docs-info-' + now.strftime("%Y-%m-%d-%H-%M-%S") + '.xlsx')

    # 加载工作簿
    wb = Workbook()
    # 激活工作表
    sheet = wb.active
    sheet.title = '文档格式错误链接'
    if not os.path.exists(git_path):
        sheet['A1'] = '本地代码仓路径错误'
        wb.save(excel_path)
        return
    sheet.append(
        ["错误文档路径", '错误原因'])
    get_md_info(sheet, git_path)
    wb.save(excel_path)


def get_md_info(sheet,git_path):
    # 判断当前路径是文件还是文件夹，是文件的话直接处理
    if os.path.isdir(git_path):
        directory_path = Path(git_path)
        for file_path in directory_path.rglob('*.md'):
            get_md_owner(file_path, sheet)
    elif os.path.isfile(git_path):
        get_md_owner(git_path, sheet)

def get_md_owner(file_path, sheet):
    print(file_path)
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            file_content = file.read()
    except UnicodeDecodeError as e:
        print(e)
        md_info_line = ['', '']
        md_info_line[0] = str(file_path)
        md_info_line[1] = "utf-8格式，读取错误"
        sheet.append(md_info_line)

if __name__ == '__main__':
    root = tk.Tk()
    app = DocCheckApp(root)
    root.mainloop()
# if __name__ == '__main__':
#     get_owner('D:\project\gitCode-test\docs\en\\application-dev\\ai\\nnrt')
